import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:fsharing/core/constants/app_contstants.dart';
import 'package:fsharing/core/viewmodels/app_model.dart';
import 'package:fsharing/core/viewmodels/pages/mine/reg_new_model.dart';
import 'package:fsharing/core/viewmodels/pages/mine/reg_new_qr_model.dart';
import 'package:fsharing/core/viewmodels/pages/mine/req_code_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fsharing/ui/pages/mine/webview_page.dart';
import 'package:fsharing/ui/widgets/background_container.dart';
import 'package:fsharing/ui/widgets/count_down_text.dart';
import 'package:fsharing/ui/widgets/round_back_button.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';

class RegisterPage extends StatefulWidget {
  @override
  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  final _inviteCodeController = TextEditingController();

  @override
  void dispose() {
    _inviteCodeController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => RegNewModel(Provider.of(context, listen: false)),
        ),
        ChangeNotifierProvider(
          create: (context) => RegNewQrModel(Provider.of(context, listen: false)),
        )
      ],
      child: BackgroundContainer(
        name: 'assets/images/all_background_oauth.png',
        child: Scaffold(
          appBar: AppBar(
            leading: RoundBackButton(),
          ),
          body: SingleChildScrollView(
            padding: EdgeInsets.symmetric(horizontal: 15),
            child: Builder(
              builder: (context) {
                RegNewModel model = Provider.of(context, listen: false);
                return Column(
                  children: <Widget>[
                    SizedBox(height: 50),
                    Text(
                      '用户注册',
                      style: TextStyle(fontSize: 28),
                    ),
                    SizedBox(height: 40),
                    Row(
                      children: <Widget>[
                        Expanded(
                          child: _WrapContainer(
                            child: TextFormField(
                              controller: _inviteCodeController,
                              decoration: InputDecoration(
                                hintText: '邀请码',
                              ),
                              onChanged: (value) {
                                model.inviteCode = value;
                              },
                            ),
                          ),
                        ),
                        SizedBox(width: 1),
                        Container(
                          alignment: Alignment.center,
                          color: Colors.white10,
                          width: 118,
                          height: 50,
                          child: FlatButton(
                            onPressed: () {
                              _onQrcodeClicked(context);
                            },
                            child: Text(
                              '扫码输入',
                              style: TextStyle(color: Colors.grey, fontSize: 16),
                            ),
                          ),
                        ),
                      ],
                    ),
                    _CheckBoxWidget(),
                    _WrapContainer(
                      margin: EdgeInsets.only(top: 15),
                      child: TextField(
                        decoration: InputDecoration(
                          hintText: '手机号',
                        ),
                        keyboardType: TextInputType.phone,
                        onChanged: (value) {
                          model.mobile = value;
                        },
                      ),
                    ),
                    SizedBox(height: 15),
                    Row(
                      children: <Widget>[
                        Expanded(
                          child: Container(
                            child: _WrapContainer(
                              child: TextField(
                                decoration: InputDecoration(
                                  hintText: '验证码',
                                ),
                                onChanged: (value) {
                                  model.checkCode = value;
                                },
                              ),
                            ),
                          ),
                        ),
                        SizedBox(width: 1),
                        Container(
                          alignment: Alignment.center,
                          color: Colors.white10,
                          width: 118,
                          height: 50,
                          child: ChangeNotifierProvider(
                            create: (context) => ReqCodeModel(Provider.of(context, listen: false)),
                            child: Consumer<ReqCodeModel>(
                              builder: (context, model, child) {
                                switch (model.viewState) {
                                  case ViewState.busy:
                                    return FlatButton(
                                      onPressed: null,
                                      child: SizedBox(
                                        width: 14,
                                        height: 14,
                                        child: CircularProgressIndicator(),
                                      ),
                                    );
                                  case ViewState.success:
                                    return FlatButton(
                                      onPressed: null,
                                      child: CountDownText(
                                        function: () {
                                          model.viewState = ViewState.idle;
                                        },
                                        style: TextStyle(color: Colors.grey, fontSize: 16),
                                      ),
                                    );
                                  default:
                                    return FlatButton(
                                      onPressed: () {
                                        _onCodeClicked(context);
                                      },
                                      child: Text(
                                        '发送验证码',
                                        style: TextStyle(color: Colors.grey, fontSize: 16),
                                      ),
                                    );
                                }
                              },
                            ),
                          ),
                        ),
                      ],
                    ),
                    Container(
                      margin: EdgeInsets.only(top: 40),
                      width: 256,
                      height: 65,
                      child: Consumer<RegNewModel>(
                        builder: (context, model, child) {
                          switch (model.viewState) {
                            case ViewState.busy:
                              return RaisedButton(
                                onPressed: null,
                                child: CircularProgressIndicator(),
                              );
                            default:
                              return RaisedButton(
                                onPressed: () {
                                  _onRegNewClicked(context);
                                },
                                child: Text(
                                  '注册',
                                  style: TextStyle(fontSize: 18),
                                ),
                              );
                          }
                        },
                      ),
                    ),
                    _QrcodeFuncWidget(),
                    Container(
                      margin: EdgeInsets.only(top: 40, bottom: 40),
                      child: RichText(
                        text: TextSpan(
                          text: '用户注册成功即表示同意',
                          style: TextStyle(color: Colors.grey),
                          children: [
                            TextSpan(
                              text: '《平台用户协议》',
                              style: TextStyle(color: Theme.of(context).accentColor),
                              recognizer: TapGestureRecognizer()
                                ..onTap = () {
                                  _onAgreementClicked(context);
                                },
                            ),
                            TextSpan(text: '内容'),
                          ],
                        ),
                      ),
                    ),
                  ],
                );
              },
            ),
          ),
        ),
      ),
    );
  }

  void _onQrcodeClicked(BuildContext context) async {
    var result = await Navigator.of(context).pushNamed('/qrcode');
    if (result == null) {
      return;
    }
    try {
      var uri = Uri.parse(result);
      var queryParameters = uri.queryParameters;
      var invitedCode = queryParameters['ic'];
      if (invitedCode == null) {
        throw '无效二维码';
      }
      RegNewModel model = Provider.of(context, listen: false);
      model.inviteCode = invitedCode;
      _inviteCodeController.text = invitedCode;
    } catch (e) {
      showToast('无效二维码');
    }
  }

  void _onCodeClicked(BuildContext context) async {
    RegNewModel regNewModel = Provider.of(context, listen: false);
    var mobile = regNewModel.mobile;

    ReqCodeModel reqCodeModel = Provider.of(context, listen: false);
    var viewState = await reqCodeModel.reqCode(ReqCodeModel.USER_REGISTER, mobile);

    switch (viewState) {
      case ViewState.error:
        showToast(reqCodeModel.errorMessage);
        break;
      default:
        showToast('验证码已发送');
        break;
    }
  }

  void _onRegNewClicked(BuildContext context) async {
    RegNewModel model = Provider.of(context, listen: false);
    var viewState = await model.regNew();
    switch (viewState) {
      case ViewState.error:
        showToast(model.errorMessage);
        break;
      default:
        await showDialog(
          context: context,
          builder: (context) {
            var data = model.data;
            return AlertDialog(
              content: Text('用户名：${data.username}\n密码：${data.originPassword}'),
              actions: <Widget>[
                FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                  child: Text('确定'),
                ),
              ],
            );
          },
        );
        Navigator.of(context).pop();
        break;
    }
  }

  void _onAgreementClicked(BuildContext context) async {
    AppStoreModel model = Provider.of(context, listen: false);
    Navigator.of(context).pushNamed(
      '/webview',
      arguments: WebViewPageArgs(
        '用户协议',
        '请仔细阅读以下条款：',
        '$api_base_url/app/protocol?sid=${model.bindingStoreId}',
      ),
    );
  }
}

/// 可选项
class _CheckBoxWidget extends StatefulWidget {
  @override
  __CheckBoxWidgetState createState() => __CheckBoxWidgetState();
}

class __CheckBoxWidgetState extends State<_CheckBoxWidget> {
  var _checkbox = false;

  @override
  Widget build(BuildContext context) {
    RegNewModel model = Provider.of(context, listen: false);
    return Column(
      children: <Widget>[
        Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: <Widget>[
            Container(
              width: 15,
              height: 15,
              margin: EdgeInsets.only(left: 5, top: 15, right: 10),
              child: Checkbox(
                  value: _checkbox,
                  onChanged: (value) {
                    model.clearOptional();
                    setState(() {
                      _checkbox = value;
                    });
                  }),
            ),
            Text(
              '自定义账号',
              style: TextStyle(color: Colors.grey, fontSize: 15),
            ),
          ],
        ),
        if (_checkbox)
          Column(
            children: <Widget>[
              _WrapContainer(
                margin: EdgeInsets.only(top: 15),
                child: TextField(
                  decoration: InputDecoration(
                    hintText: '用户账号',
                  ),
                  onChanged: (value) {
                    model.username = value;
                  },
                ),
              ),
              _WrapContainer(
                margin: EdgeInsets.only(top: 6),
                child: TextField(
                  decoration: InputDecoration(
                    hintText: '用户密码',
                  ),
                  obscureText: true,
                  onChanged: (value) {
                    model.password = value;
                  },
                ),
              ),
              _WrapContainer(
                margin: EdgeInsets.only(top: 6),
                child: TextField(
                  decoration: InputDecoration(
                    hintText: '确认密码',
                  ),
                  obscureText: true,
                  onChanged: (value) {
                    model.passwordConfirm = value;
                  },
                ),
              ),
            ],
          )
      ],
    );
  }
}

class _QrcodeFuncWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<RegNewQrModel>(
      builder: (context, model, child) {
        switch (model.viewState) {
          case ViewState.busy:
            return FlatButton(
              onPressed: null,
              child: SizedBox(
                width: 14,
                height: 14,
                child: CircularProgressIndicator(),
              ),
            );
          default:
            return FlatButton.icon(
              onPressed: () {
                _onQrcodeClicked(context);
              },
              icon: Icon(
                Icons.filter_center_focus,
                size: 16,
              ),
              label: Text('扫码注册'),
            );
        }
      },
    );
  }

  void _onQrcodeClicked(BuildContext context) async {
    var result = await Navigator.of(context).pushNamed('/qrcode');
    if (result == null) {
      return;
    }
    try {
      var uri = Uri.parse(result);
      var queryParameters = uri.queryParameters;
      var encodedClientId = queryParameters['client_id'];
      var invitedCode = queryParameters['ic'];
      if (encodedClientId == null || invitedCode == null) {
        throw '无效二维码';
      }
      RegNewQrModel model = Provider.of(context, listen: false);
      var viewState = await model.regNewQr(encodedClientId, invitedCode);
      switch (viewState) {
        case ViewState.error:
          showToast(model.errorMessage);
          break;
        default:
          showDialog(
            context: context,
            builder: (context) {
              var data = model.data;
              return AlertDialog(
                content: Text('用户名：${data.username}\n密码：${data.originPassword}'),
                actions: <Widget>[
                  FlatButton(
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    child: Text('确定'),
                  ),
                ],
              );
            },
          );
          break;
      }
    } catch (e) {
      debugPrint('e = $e');
      showToast('无效二维码');
    }
  }
}

class _WrapContainer extends StatelessWidget {
  final EdgeInsetsGeometry margin;
  final Widget child;

  _WrapContainer({
    Key key,
    this.margin,
    this.child,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      padding: EdgeInsets.symmetric(horizontal: 16),
      color: Colors.white10,
      height: 50,
      margin: margin,
      child: child,
    );
  }
}
